package site.kitcheng.springboottest.infra.utils;

import site.kitcheng.springboottest.infra.constant.BaseConstant;

import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;

/**
 * ClassName: RSAEncryptWithSalt
 * Package: site.kitcheng.springboottest.infra.utils
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/2/24 11:23
 * @Version 1.0
 */
public class RSAEncryptWithSalt {

    // 生成盐值
    public static String generateSalt() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] salt = new byte[16];  // 16字节的盐值
        secureRandom.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 使用RSA公钥加密，并附加盐值
    public static String encryptWithSalt(String data, PublicKey publicKey) throws Exception {
        // 生成盐值
        String salt = generateSalt();

        // 拼接盐值和数据
        String dataWithSalt = salt + data;

        // 使用RSA加密
        Cipher cipher = Cipher.getInstance(BaseConstant.ENCRYPTION_ALGORITHMS);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(dataWithSalt.getBytes());

        // 返回盐值和加密后的数据
        String encryptedString = Base64.getEncoder().encodeToString(encryptedData);
        return salt + BaseConstant.PASSWORD_SEPARATOR + encryptedString;
    }




}
